<?php


/********************************************/
/** STANDARD MESSAGE HANDLING & FORMATTING **/
/********************************************/

function prnMsg($Msg,$Type='info', $Prefix=''){

	echo getMsg($Msg, $Type, $Prefix);

}//prnMsg

function getMsg($Msg,$Type='info',$Prefix=''){
	$Colour='';
	switch($Type){
		case 'error':
			$Class = 'error';
			$Prefix = $Prefix ? $Prefix : _('ERROR') . ' ' ._('Message Report');
			break;
		case 'warn':
			$Class = 'warn';
			$Prefix = $Prefix ? $Prefix : _('WARNING') . ' ' . _('Message Report');
			break;
		case 'success':
			$Class = 'success';
			$Prefix = $Prefix ? $Prefix : _('SUCCESS') . ' ' . _('Report');
			break;
		case 'info':
		default:
			$Prefix = $Prefix ? $Prefix : _('INFORMATION') . ' ' ._('Message');
			$Class = 'info';
	}
	return '<DIV class="'.$Class.'"><B>' . $Prefix . '</B> : ' .$Msg . '</DIV>';
}//getMsg

function IsEmailAddress($TestEmailAddress){

/*thanks to Gavin Sharp for this regular expression to test validity of email addresses */

	if (function_exists('preg_match')){
		if(preg_match("/^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6}$/", $TestEmailAddress)){
			return true;
		} else {
			return false;
		}
	} else {
		if (strlen($TestEmailAddress)>5 AND strstr($TestEmailAddress,'@')>2 AND (strstr($TestEmailAddress,'.co')>3 OR strstr($TestEmailAddress,'.org')>3 OR strstr($TestEmailAddress,'.net')>3 OR strstr($TestEmailAddress,'.edu')>3 OR strstr($TestEmailAddress,'.biz')>3)){
			return true;
		} else {
			return false;
		}
	}
}


Function ContainsIllegalCharacters ($CheckVariable) {

	if (strstr($CheckVariable,"'")
		OR strstr($CheckVariable,'+')
		OR strstr($CheckVariable,"\"")
		OR strstr($CheckVariable,'&')
		OR strstr($CheckVariable,"\\")
		OR strstr($CheckVariable,'"')){

		return true;
	} else {
		return false;
	}
}


function pre_var_dump(&$var){
	echo "<div align=left><pre>";
	var_dump($var);
	echo "</pre></div>";
}



class XmlElement {
  var $name;
  var $attributes;
  var $content;
  var $children;
};

function GetECBCurrencyRates () {
/* See http://www.ecb.int/stats/exchange/eurofxref/html/index.en.html
for detail of the European Central Bank rates - published daily */
	  $xml = file_get_contents('http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml');  
	  $parser = xml_parser_create();
	  xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
	  xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
	  xml_parse_into_struct($parser, $xml, $tags);
	  xml_parser_free($parser);

	  $elements = array();  // the currently filling [child] XmlElement array
	  $stack = array();
	  foreach ($tags as $tag) {
		$index = count($elements);
		if ($tag['type'] == "complete" || $tag['type'] == "open") {
		  $elements[$index] = new XmlElement;
		  $elements[$index]->name = $tag['tag'];
		  $elements[$index]->attributes = $tag['attributes'];
		  $elements[$index]->content = $tag['value'];
		  if ($tag['type'] == "open") {  // push
			$elements[$index]->children = array();
			$stack[count($stack)] = &$elements;
			$elements = &$elements[$index]->children;
		  }
		}
		if ($tag['type'] == "close") {  // pop
		  $elements = &$stack[count($stack) - 1];
		  unset($stack[count($stack) - 1]);
		}
	  }
	 
	  
	  $Currencies = array();
	  foreach ($elements[0]->children[2]->children[0]->children as $CurrencyDetails){
		$Currencies[$CurrencyDetails->attributes['currency']]= $CurrencyDetails->attributes['rate'] ;
	  }
	  $Currencies['EUR']=1; //ECB delivers no rate for Euro
	  //return an array of the currencies and rates
	  return $Currencies;
}	
	
function GetCurrencyRate($CurrCode,$CurrenciesArray) {
  if ((!isset($CurrenciesArray[$CurrCode]) or !isset($CurrenciesArray[$_SESSION['CompanyRecord']['currencydefault']]))){
  	return quote_oanda_currency($CurrCode);
  } elseif ($CurrCode=='EUR'){
  	if ($CurrenciesArray[$_SESSION['CompanyRecord']['currencydefault']]==0) {
  		return 0;
  	} else {
  		return 1/$CurrenciesArray[$_SESSION['CompanyRecord']['currencydefault']];
  	}
  }	else {
  	if ($CurrenciesArray[$_SESSION['CompanyRecord']['currencydefault']]==0) {
  		return 0;
  	} else {
  		return $CurrenciesArray[$CurrCode]/$CurrenciesArray[$_SESSION['CompanyRecord']['currencydefault']];
  	}
  }
}

function quote_oanda_currency($CurrCode) {
	$page = file('http://www.oanda.com/convert/fxdaily?value=1&redirected=1&exch=' . $CurrCode .  '&format=CSV&dest=Get+Table&sel_list=' . $_SESSION['CompanyRecord']['currencydefault']);
	$match = array();
	preg_match('/(.+),(\w{3}),([0-9.]+),([0-9.]+)/i', implode('', $page), $match);

	if ( sizeof($match) > 0 ){
      	  	return $match[3];
	} else {
      	   	return false;
	}
}


function AddCarriageReturns($str) {
	return str_replace('\r\n',chr(10),$str); 
}


function wikiLink($type, $id) {
	
	if ($_SESSION['WikiApp']==_('WackoWiki')){
	echo '<a target="_blank" href="../' . $_SESSION['WikiPath'] . '/' . $type .  $id . '">' . _('Wiki ' . $type . ' Knowlege Base') . '</A><BR>';
	} elseif ($_SESSION['WikiApp']==_('MediaWiki')){
		echo '<a target="_blank" href="../' . $_SESSION['WikiPath'] . '/index.php/' . $type . '/' .  $id . '">' . _('Wiki ' . $type . ' Knowlege Base') . '</A><BR>';
	}

}//wikiLink

function explodeX($delimiters,$string)
{
    $return_array = Array($string); // The array to return
    $d_count = 0;
    while (isset($delimiters[$d_count])) // Loop to loop through all delimiters
    {
        $new_return_array = Array();
        foreach($return_array as $el_to_split) // Explode all returned elements by the next delimiter
        {
            $put_in_new_return_array = explode($delimiters[$d_count],$el_to_split);
            foreach($put_in_new_return_array as $substr) // Put all the exploded elements in array to return
            {
                $new_return_array[] = $substr;
            }
        }
        $return_array = $new_return_array; // Replace the previous return array by the next version
        $d_count++;
    }
    return $return_array; // Return the exploded elements
}

function getArrayNameOfNumber(){
		return array(
			0=>"không",
			1=>"một",
			2=>"hai",
			3=>"ba",
			4=>"bốn",
			5=>"năm",
			6=>"sáu",
			7=>"bảy",
			8=>"tám",
			9=>"chín",
			10=>"mười",
			11=>"mốt",
			12=>"lẻ",
			13=>"lăm",
			14=>"mươi",
			15=>"trăm",
			16=>"ngàn",
			17=>"triệu",
			18=>"tỷ",
			19=>"ngàn tỷ",
			20=>"đồng",
			21=>"phẩy");
	}
	
/*
	 * ham cat chuoi trai hay phai
	 */
	function  right($value, $count){
	    return substr($value, ($count*-1));
	}

	function  left($string, $count){
	    return substr($string, 0, $count);
	}

	function  execConvertNumToStr($sodoi){
		$arrayChuSo = getArrayNameOfNumber();

		$chuoiso = '';
		$kitutram = '';
		$kituchuc = '';
		$kitudonvi = '';
		// tach tung ky tu
		$kitutram = substr($sodoi, 0, 1);//echo " ".$kitutram;
		$kituchuc = substr($sodoi, 1, 1);//echo " ".$kituchuc;
		$kitudonvi = substr($sodoi, 2, 1);//echo " ".$kitudonvi;

		$chuoiso = $arrayChuSo[intval($kitutram)] . ' ' . $arrayChuSo[15];

		// neu gi tri 100 thi tra ve mot tram
		if (($kituchuc == '0') && ($kitudonvi == '0')){
			return $chuoiso;
		}

		// bat dau chuyen doi neu gia tri khac 100
		if (($kituchuc == '0') && ($kitudonvi != '0')){  // hang chuc le
		    $chuoiso = $chuoiso . ' ' . $arrayChuSo[12] . ' ' . $arrayChuSo[intval($kitudonvi)];
		}else{
			if ($kituchuc == '1'){ // hang chuc duoc doc la muoi
			    if ($kitudonvi == '5')
					$chuoiso = $chuoiso . ' ' . $arrayChuSo[10] . ' ' . $arrayChuSo[13];
		     	else if ($kitudonvi == '0')
					$chuoiso = $chuoiso . ' ' . $arrayChuSo[10];
				else
					$chuoiso = $chuoiso . ' ' . $arrayChuSo[10] . ' ' . $arrayChuSo[intval($kitudonvi)];

		    }else{
				$chuoiso = $chuoiso . ' ' . $arrayChuSo[intval($kituchuc)] . ' ' . $arrayChuSo[14];
		      	if ($kitudonvi == '1') // doc la mốt
					$chuoiso = $chuoiso . ' ' . $arrayChuSo[11];
		        else if ($kitudonvi == '5') // doc la lăm
					$chuoiso = $chuoiso . ' ' . $arrayChuSo[13];
		      	else if ($kitudonvi != '0') // doc la binh thuong
	   		     	     $chuoiso = $chuoiso .' '. $arrayChuSo[intval($kitudonvi)];
			}
		}

		return $chuoiso;
	}
	
function convertNumberToString($socandoi){

		$arrayChuSo = getArrayNameOfNumber();
		$dayphay = '';
		$chuoidauphay = '';
		$posOfDecimal = strpos($socandoi, '.');
		if($posOfDecimal > 0){
			$soThapPhan = substr($socandoi, $posOfDecimal+1, strlen($socandoi));
			$chuoidauphay = $arrayChuSo[21].' '.$arrayChuSo[substr($soThapPhan, 0, 1)];

			if(substr($soThapPhan, 1, 1) != '0'){
				$chuoidauphay .= ' '.$arrayChuSo[14].' '.$arrayChuSo[substr($soThapPhan, 1, 1)];
			}

			$socandoi = substr($socandoi, 0, $posOfDecimal);
		}

		$arrayChuSo = getArrayNameOfNumber();

		$indaychuso = '';
		$lenSocandoi = strlen($socandoi);
		$kisodoi = '';



		if(strlen($socandoi) > 13){
			echo "so qua lon";
		}else{
			while($lenSocandoi < 13){
				$kisodoi = $kisodoi.'0';
			    $lenSocandoi = $lenSocandoi + 1;
			}

			$kisodoi = $kisodoi.$socandoi;
			//echo $kisodoi." ";
			$phannganty = substr($kisodoi, 0, 1);//echo $phannganty;
			$phanty = substr($kisodoi, 1, 3);//echo $phanty;
			$phantrieu = substr($kisodoi, 4, 3);//echo $phantrieu." ";
			$phanngan = substr($kisodoi, 7, 3);//echo $phanngan." ";
			$phantram = substr($kisodoi, 10, 3);//echo $phantram." ";

			if (($phannganty == '0') && ($phanty == '000') && ($phantrieu == '000') && ($phanngan == '000') && ($phantram == '000')) {

			    $indaychuso = $arrayChuSo[0];
			}else{

				if($phannganty != '0'){

					$indaychuso = $arrayChuSo[intval($phannganty)] . ' ' . $arrayChuSo[16];

					if($phanty == '000') $indaychuso = $indaychuso . ' ' . $arrayChuSo[18] . $dayphay;
					if ($phanty != '000') $indaychuso = $indaychuso . ' ' . execConvertNumToStr($phanty). ' '. $arrayChuSo[18] . $dayphay;
					if ($phantrieu != '000') $indaychuso = $indaychuso . ' '. execConvertNumToStr($phantrieu). ' '. $arrayChuSo[17] . $dayphay;
					if ($phanngan != '000') $indaychuso = $indaychuso . ' ' . execConvertNumToStr($phanngan) . ' ' . $arrayChuSo[16] . $dayphay;
					if ($phantram != '000') $indaychuso = $indaychuso . ' '. execConvertNumToStr($phantram) ;
				}

				if (($phannganty == '0') && ($phanty != '000')){

					$indaychuso = execConvertNumToStr($phanty);

					if(left($phanty,2) == '00') $indaychuso = mb_substr($indaychuso, 14, 20, 'UTF-8');

					//echo left($phanty,1);
					//echo substr($phanty, 2, 1);

					if((left($phanty,1) == '0') &&
					(substr($phanty, 1, 1) != '0')) {

						$indaychuso = mb_substr($indaychuso, 11, 20, 'UTF-8');

					}

					$indaychuso = $indaychuso. ' '. $arrayChuSo[18]. $dayphay ;


					if ($phantrieu != '000') $indaychuso = $indaychuso . ' '. execConvertNumToStr($phantrieu). ' '. $arrayChuSo[17]. $dayphay;
					if ($phanngan != '000') $indaychuso = $indaychuso . ' '. execConvertNumToStr($phanngan). ' '. $arrayChuSo[16]. $dayphay;
					if ($phantram != '000') $indaychuso = $indaychuso . ' '. execConvertNumToStr($phantram) ;

				}


				if (($phannganty == '0') && ($phanty == '000') && ($phantrieu !='000')){
					$indaychuso = execConvertNumToStr($phantrieu);

					if(left($phantrieu,2) == '00') $indaychuso = mb_substr($indaychuso, 14, 20, 'UTF-8');
					if((left($phantrieu,1) == '0') && (substr($phantrieu, 1, 1) != '0')) $indaychuso = mb_substr($indaychuso, 11, 20, 'UTF-8')  ;
					$indaychuso = $indaychuso. ' '. $arrayChuSo[17]. $dayphay ;
					if ($phanngan != '000') $indaychuso = $indaychuso . ' '. execConvertNumToStr($phanngan). ' '. $arrayChuSo[16]. $dayphay;
					if ($phantram != '000') $indaychuso = $indaychuso . ' '. execConvertNumToStr($phantram) ;
			    }

				if (($phannganty == '0') && ($phanty == '000') && ($phantrieu == '000') && ($phanngan !='000')){

					$indaychuso = execConvertNumToStr($phanngan);
					if(left($phanngan,2) == '00') $indaychuso = mb_substr($indaychuso, 14, 20, 'UTF-8');
					if((left($phanngan,1) == '0') && (substr($phanngan, 1, 1) != '0')) $indaychuso = mb_substr($indaychuso, 11, 20, 'UTF-8');
					$indaychuso = $indaychuso. ' '. $arrayChuSo[16] ;
					if ($phantram != '000') $indaychuso = $indaychuso . ' '. execConvertNumToStr($phantram) ;
				}

				if (($phannganty == '0') && ($phanty == '000') && ($phantrieu =='000') && ($phanngan =='000') && ($phantram !='000'))	{

					$indaychuso = execConvertNumToStr($phantram)	;
					if(left($phantram,2) == '00') $indaychuso = mb_substr($indaychuso, 14, 20, 'UTF-8');
					if((left($phantram,1) == '0') && (substr($phantram, 1, 1) != '0')) $indaychuso = mb_substr($indaychuso, 11, 20, 'UTF-8');
					$indaychuso = $indaychuso;
			    }

		        $indaychuso = $indaychuso. ' ' . $chuoidauphay . ' '.$arrayChuSo[20];

			}
		}
		return $indaychuso;
	}
?>